<template>
  <div class="wrapper">
    <!--ToDo:这里append-to-body 和 model-append-to-body 暂时没弄true，但似乎会影响 弹出选择数据得显示层问题-->
    <el-dialog :title="title" :width="width" :visible.sync="isShowDialog" :close-on-click-modal="false">
      <dan-form ref="mainForm" :formTypeProp="formTypeProp" :formWidth="width" :formSize="formSize" :formData="formData" @tapTemp="tapTempMain"></dan-form>
      <el-tabs v-model="activeTabName" type="card" @tab-click="tapTabs" v-if="formSubData.length > 0">
          <el-tab-pane :label="group.formTitle" :name="group.formTitle" v-for="(group,groupIndex) in formSubData" :key="group.formTitle">
            <dan-form ref="subForm" :formTypeProp="formTypeProp" :formWidth="width" :formSize="formSize" :formData="group.formData" @tapTemp="(e)=>tapTempSub(groupIndex,e)"></dan-form>
          </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <template v-if="formTypeProp == 'look'">
          <el-button type="primary" @click="closeForm">关 闭</el-button>
        </template>
        <template v-else>
          <el-button @click="closeForm">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </template>
        
      </div>
    </el-dialog>

    <el-dialog title="模板选择" width="450px" :visible.sync="isShowTemp" :close-on-click-modal="false" :append-to-body="true" :modal-append-to-body="true">
      {{tempName}}模板：
      <el-select  v-model="tempValue" placeholder="请选择模板" :filterable="true" clearable>
        <el-option
          v-for="(item,index) in tempData"
          :key="tempOptions.optionsValueField ? item[tempOptions.optionsValueField] : item.value"
          :label="tempOptions.optionsLabelField ? item[tempOptions.optionsLabelField] : item.label"
          :value="index">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTemp">取 消</el-button>
        <el-button type="primary" @click="submitTemp">取 用</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.my-autocomplete li {line-height: normal;padding: 7px;}
.name {text-overflow: ellipsis; overflow: hidden;}
.addr {font-size: 12px;color: #b4b4b4;}
.highlighted .addr {color: #ddd;}
.dialog-form{padding:20px 50px 5px 20px;}
.dialog-form-sub{padding:20px 50px 5px 20px;}
.dialog-footer{display: flex;justify-content: flex-end;}

</style>
<style>

</style>
<script>
import {editData,addData,getEdit,getSelectData } from '@/api/common.js';
import {setTempText,isArray, isString} from '@/utils';

import Tinymce from '@/components/Tinymce';
import uploadImageDrag from '@/components/common/uploadImageDrag';
import danForm from '@/components/common/danForm';
export default {
  components:{danForm,Tinymce,uploadImageDrag},
  props:{
    controller:{
      type:String,
      default(){
        return '';
      }
    },
    formTitle:{
      type:String,
      default(){
        return '';
      }
    },
    formSize:{
      type:String,
      default(){
        return '';
      }
    },
    formData:{
      type:Object,
      default(){
        return {};
      }
    },
    formSubData:{
      type:Array,
      default(){
        return [];
      }
    },
    formWidth:{
      type:String,
      default(){
        return '500px';
      }
    },
    formTypeProp:{
      type:String,
      default(){
        return 'add';
      }
    },
    addActionProp:{
      type:String,
      default(){
        return '';
      }
    },
    getEditActionProp:{
      type:String,
      default(){
        return '';
      }
    },
    editActionProp:{
      type:String,
      default(){
        return '';
      }
    }
  },
  data(){
    return {
      id:0,
      isShowDialog:false,
      form:{},
      formSub:[],
      uploadUrl:this.$config.requestUrl+'/' + this.$config.app+'/' + this.$config.version + '/Upload/uploadImage',
      uploadHeaders:this.$store.getters.userInfo.user_token ? {'User-Token' :this.$store.getters.userInfo.user_token} : {},
      activeTabName:'',
      addAction:'',
      editAction:'',
      getEditAction:'',
      formType:'',
      requestParams:{},
      editData:{},
      width:'',
      isShowTemp:false,
      tempField:'',
      tempOptions:{},
      tempData:{},
      tempValue:'',
      tempName:''
    }
  },
  created(){
    this.formType = this.formTypeProp;
    this.addAction = this.addActionProp;
    this.editAction = this.editActionProp;
    this.getEditAction = this.getEditActionProp;
    if (this.formSize == 'small') {
      this.width = '500px';
    } else if (this.formSize == 'big'){
      this.width = '1280px';
    } else {
      this.width = '960px';
    }
    //this.initForm();因为打开要初始化，暂时重复了
  },
  mounted(){

  },
  methods:{
    tapTabs(tab, event) {

    },
    initForm(id){
      this.isShowDialog = true;
      this.id = id;
      return new Promise((resolve,reject)=>{
        this.$nextTick(()=>{
          this.$refs.mainForm.initForm();
          if (this.$refs.subForm) this.$refs.subForm.forEach(item=>{
            item.initForm();
          })
          //如果存在富文本，重置富文本显示内容
          let tinymces = window.tinymce ? window.tinymce.get() : [];
          tinymces.forEach(item=>item.setContent(''));
          this.activeTabName = this.formSubData[0] ? this.formSubData[0].formTitle : '';

          //如果传了ID，代表编辑或复制，获取数据，赋值
          if (id) {
            let actionUrl,params = {};
            for (let k in this.$route.query) {
              params[k] = this.$route.query[k];
            }
            if (this.$system.requestApiStyle == 'restful'){
              actionUrl = this.getEditAction ? this.getEditAction : this.controller + '';
              if (isArray(this.resource)){
                console.log('还未做多资源格式的处理');
              } else if (isString(this.resource)){
                if (this.resource) actionUrl += '/'+id;
              }
              params.method = 'GET';
            } else {
              actionUrl = this.getEditAction ? this.getEditAction : this.controller + '/getEditData';
              params.data = {id};
              params.method = 'POST';
            }
            getEdit(actionUrl,params).then(data=>{
              this.editData = data;
              this.$refs.mainForm.updateForm(data);
              if (this.$refs.subForm) this.$refs.subForm.forEach(item=>{
                item.updateForm(data);
              })
              resolve();
            })
          } else {
            resolve();
          }
        });
      });
      
    },
    getSelectData(item){
      //获取下拉选择数据的数据源
      if (item.dataController) {
        getSelectData(item.dataController).then(data=>{
          item.options = data;
        });
      }
    },
    closeForm(){
      //关闭表单
      this.isShowDialog = false;
    },
    openForm(id){
      //打开表单
      this.initForm(id);
      
    },
    isOpen(){
      //获取当前表单状态
      return this.isShowDialog;
    },
    submit(){
      let mainForm = this.$refs.mainForm.getFormData();
      //获取表单数据
      let data = {};
      for (let key in mainForm) {
        if (mainForm[key].type == 'cascaderRadio') {
          if (mainForm[key].value)  {
            if ((typeof mainForm[key].value) == 'object'){
              data[key] = mainForm[key].value.length > 0 ? mainForm[key].value[mainForm[key].value.length - 1] : '';
            } else {
              data[key] = mainForm[key].value;
            }
            
          } else {
            data[key] = '';
          }
        } else if (mainForm[key].type == 'pics'){
          data[key] = mainForm[key].value.length > 0 ? mainForm[key].value : '';
        } else if (mainForm[key].type == 'attr') {
          data[key + '_kind'] = mainForm[key].value;
          data[key + '_data'] = mainForm[key].attrData;
        } else {
          data[key] = mainForm[key].value == '0' || mainForm[key].value ? mainForm[key].value : '';
        }

      }
      this.formSubData.forEach((group,groupIndex)=>{
        let subForm = this.$refs['subForm'][groupIndex].getFormData();
        for (let key in subForm) {
          if (subForm[key].type == 'cascaderRadio') {
            if (subForm[key].value && (typeof subForm[key].value) == 'object')  {
              data[key] = subForm[key].value.length > 0 ? subForm[key].value[subForm[key].value.length - 1] : '';
            } else {
              data[key] = '';
            }
          } else if (subForm[key].type == 'pics'){
            data[key] = subForm[key].value.length > 0 ? subForm[key].value : '';
          } else if (subForm[key].type == 'attr') {
            data[key + '_kind'] = subForm[key].value;
            data[key + '_data'] = subForm[key].attrData;
          } else {
            data[key] = subForm[key].value == '0' || subForm[key].value ? subForm[key].value : '';
          }
          
        }
      })
      for (let key in this.requestParams) {
        data[key] = this.requestParams[key];
      }
      data.query = {};
      for (let k in this.$route.query) {
        data.query[k] = this.$route.query[k];
      }
      if(this.formType == 'edit') {
        data.id = this.id;
        let actionUrl = this.editAction ? this.editAction : this.controller + '/editData';
        editData(actionUrl,data).then(data=>{
          this.$tool.succToast( '操作成功');
          this.closeForm();
          this.$emit('submitSuccess');
        });
      } else {
        let actionUrl = this.addAction ? this.addAction : this.controller + '/addData';
        addData(actionUrl,data).then(data=>{
          this.$tool.succToast('新增成功');
          this.closeForm();
          this.$emit('submitSuccess');
        });
      }
      
    },
    setAddAction(action){
      this.addAction = action;
    },
    setEditAction(action){
      this.editAction = action;
    },
    setGetEditAction(action){
      this.getEditAction = action;
    },
    setGetDataAction(){

    },
    setFormType(formType) {
      this.formType = formType;
    },
    setParams(params){
      this.requestParams = params;
    },
    //模板选择部分开始
    closeTemp(){
      this.isShowTemp = false;
    },
    submitTemp(){
      if (this.tempFormType == 'mainForm'){
        let value = this.tempData[this.tempValue][this.formData[this.tempField].tempOptions.dataField];
        if (this.formData[this.tempField].type == 'tags' && this.formData[this.tempField].limit && value.length > this.formData[this.tempField].limit) {
          value = value.splice(0,this.formData[this.tempField].limit);
        }
        this.$refs.mainForm.updateFieldValue(this.tempField,value);
      } else {
        let value = this.tempData[this.tempValue][this.formSubData[this.tempFormIndex].formData[this.tempField].tempOptions.dataField];
        if (this.formSubData[this.tempFormIndex].formData[this.tempField].type == 'tags' && this.formSubData[this.tempFormIndex].formData[this.tempField].limit && value.length > this.formSubData[this.tempFormIndex].formData[this.tempField].limit) {
          value = value.splice(0,this.formSubData[this.tempFormIndex].formData[this.tempField].limit);
        }
        this.$refs.subForm[this.tempFormIndex].updateFieldValue(this.tempField,value);
      }
    
      this.isShowTemp = false;
    },
    tapTempMain(field){
      this.tempFormType = 'mainForm';
      this.tempFormIndex = '';
      this.showTempPicker(field);
    },
    tapTempSub(subFormIndex,field){
      this.tempFormType = 'subForm';
      this.tempFormIndex = subFormIndex;
      this.showTempPicker(field);
    },
    showTempPicker(field){
      let c;
      if (this.tempFormType == 'mainForm') {
        c = this.formData[field].tempOptions && this.formData[field].tempOptions.dataController ? this.formData[field].tempOptions.dataController : '';
      } else {
        c = this.formSubData[this.tempFormIndex].formData[field].tempOptions && this.formSubData[this.tempFormIndex].formData[field].tempOptions.dataController ?  this.formSubData[this.tempFormIndex].formData[field].tempOptions.dataController : '';
      }
      if (!c) return this.$tool.toast('未配置模板属性');
      this.$tool.loading('请在读取模板信息');
      this.tempField = field;
      this.tempValue = '';
      this.tempName = this.tempFormType == 'mainForm' ? this.formData[field].label :  this.formSubData[this.tempFormIndex].formData[field].label;
      this.isShowTemp = true;
      let params = {
        c
      }
      this.$request(params).then(data=>{
        this.tempData = data;
        this.$tool.loading();
      })
      
    }
    //模板选择的部分结束
  },
  computed:{
    title(){
      let formTitle = setTempText(this.formTitle,this.editData);
      return formTitle ? formTitle : (this.formType == 'edit' ? '编辑内容' : '新增内容');
    }
  }
}


</script>